package com.heima.kafka.stream;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Arrays;

@Configuration
@Slf4j
public class KafkaStreamHelloListener {
    @Bean
    public KStream<String,String> kStream(StreamsBuilder streamsBuilder){
        //创建kstream对象，同时指定从那个topic中接收消息
        KStream<String, String> stream = streamsBuilder.stream("itcast-topic-input");
        /**
         * 处理消息的value
         */
        stream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
            @Override
            public Iterable<String> apply(String value) {
                return Arrays.asList(value.split(" "));   //根据空格把value分割成hello，kafka
            }
        })
                //根据value进行聚合分组
                .groupBy((key, value) -> value)
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))    //聚合计算时间间隔，每10s处理一次
                .count()     //求单词的个数
                .toStream()     //转换为kStream
                //处理后的结果转换为string字符串
                .map((key, value) -> {
                    System.out.println("key: " + key + ",value: " + value);
                    return new KeyValue<>(key.key().toString(), value.toString());    //将 key 和 value 转成字符串
                }).to("itcast-topic-out");    //发送消息
        return stream;
    }}
